//
//  CMPasterView.m
//  CropImg
//
//  Created by lipeng on 16/3/7.
//  Copyright © 2016年 lipeng. All rights reserved.
//

#import "CMPasterView.h"
#import "CMPasterCenterView.h"

#define PASTER_SLIDE        150.0 //paster_slide
#define FLEX_SLIDE          15.0  //flex_slide
#define BT_SLIDE            30.0  //bt_slide
#define BORDER_LINE_WIDTH   1.0   //border_line_width
#define SECURITY_LENGTH     75.0  //security_length

@interface CMPasterView()
{
    CGFloat minWidth;
    CGFloat minHeight;
    CGFloat deltaAngle;
    CGPoint prevPoint;
    CGPoint touchStart;
    CGRect bgRect;
}

@property (nonatomic, strong) UIImageView *imgContentView;
@property (nonatomic, strong) UIImageView *btnDelete;
@property (nonatomic, strong) UIImageView *btnSizeCtrl;

@end



@implementation CMPasterView

#pragma mark - Initial(初始化)
-(instancetype)initWithBgView:(CMPasterCenterView *)bgView
                     pasterID:(int)pasterID
                          img:(UIImage *)img
{
    self = [super init];
    if(self)
    {
        self.pasterID = pasterID;
        self.imagePaster = img;
        
        bgRect = bgView.frame;
        
        [self setupWithBGFrame:bgRect];
        [self imgContentView];
        [self btnDelete];
        [self btnSizeCtrl];
        [bgView addSubview:self];
        
        self.isOnFirst = YES;
        
    }
    return self;
}

-(void)remove
{
    [self removeFromSuperview];
    
    if([self.delegate respondsToSelector:@selector(removePaster:)])
        [self.delegate removePaster:self.pasterID];
}

-(void)setupWithBGFrame:(CGRect)bgFrame
{
    CGRect rect = CGRectZero;
    rect.size = CGSizeMake(PASTER_SLIDE, PASTER_SLIDE);
    self.frame = rect;
    self.center = CGPointMake(bgFrame.size.width/2, bgFrame.size.height/2);
    self.backgroundColor = nil;
    
    //点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
                                          initWithTarget:self
                                          action:@selector(handleTap:)];
    [self addGestureRecognizer:tapGesture];
    
//    UIPinchGestureRecognizer *pincheGesture = [[UIPinchGestureRecognizer alloc]
//                                               initWithTarget:self
//                                               action:@selector(handlePinch:)];
//    [self addGestureRecognizer:pincheGesture];
    
    //旋转手势
    UIRotationGestureRecognizer *rotateGesture = [[UIRotationGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(handleRotation:)];
    [self addGestureRecognizer:rotateGesture];
    
    
    self.userInteractionEnabled = YES;
    
    minWidth = self.bounds.size.width * 0.5;
    minHeight = self.bounds.size.height * 0.5;
    
    deltaAngle = atan2(self.frame.origin.y+self.frame.size.height - self.center.y,
                       self.frame.origin.x+self.frame.size.width - self.center.x);
    
}

#pragma mark - Gesture(手势事件)
-(void)handleTap:(UITapGestureRecognizer *)tapGesture
{
    NSLog(@"tap paster become first respond");
    self.isOnFirst = YES;
    
    if([self.delegate respondsToSelector:@selector(makePasterBecomeFirst:)])
        [self.delegate makePasterBecomeFirst:self.pasterID];
}

-(void)handlePinch:(UIPinchGestureRecognizer *)pichGesture
{
    self.isOnFirst = YES;
    
    if([self.delegate respondsToSelector:@selector(makePasterBecomeFirst:)])
        [self.delegate makePasterBecomeFirst:self.pasterID];
    
    self.imgContentView.transform = CGAffineTransformScale(self.imgContentView.transform,
                                                           pichGesture.scale, pichGesture.scale);
    pichGesture.scale = 1;
}

-(void)handleRotation:(UIRotationGestureRecognizer *)rotateGesture
{
    self.isOnFirst = YES;
    
    if([self.delegate respondsToSelector:@selector(makePasterBecomeFirst:)])
        [self.delegate makePasterBecomeFirst:self.pasterID];
    
    self.transform = CGAffineTransformRotate(self.transform, rotateGesture.rotation);
    rotateGesture.rotation = 0;
}

-(void)resizeTranslate:(UIPanGestureRecognizer *)panGesture
{
    if([panGesture state] == UIGestureRecognizerStateBegan)
    {
        prevPoint = [panGesture locationInView:self];
        [self setNeedsDisplay];
    }
    else if([panGesture state] == UIGestureRecognizerStateChanged)
    {
        if(self.bounds.size.width < minWidth || self.bounds.size.height < minHeight)
        {
            self.bounds = CGRectMake(self.bounds.origin.x,
                                     self.bounds.origin.y,
                                     minWidth + 1,
                                     minHeight + 1);
            self.btnSizeCtrl.frame = CGRectMake(self.bounds.size.width-BT_SLIDE,
                                                self.bounds.size.height-BT_SLIDE,
                                                BT_SLIDE,
                                                BT_SLIDE);
            prevPoint = [panGesture locationInView:self];
        }
        else
        {
            CGPoint point = [panGesture locationInView:self];
            float wChange = 0.0, hChange = 0.0;
            
            wChange = (point.x - prevPoint.x);
            float wRationChange = (wChange/(float)self.bounds.size.width);
            
            hChange = wRationChange * self.bounds.size.height;
            
            if(ABS(wChange) > 50.0f || ABS(hChange) > 50.0f)
            {
                prevPoint = [panGesture locationOfTouch:0 inView:self];
                return;
            }
            
            CGFloat finalWidth = self.bounds.size.width + wChange;
            CGFloat finalHeight = self.bounds.size.height + wChange;
            
            if (finalWidth > PASTER_SLIDE*(1+0.5))
            {
                finalWidth = PASTER_SLIDE*(1+0.5) ;
            }
            if (finalWidth < PASTER_SLIDE*(1-0.5))
            {
                finalWidth = PASTER_SLIDE*(1-0.5) ;
            }
            if (finalHeight > PASTER_SLIDE*(1+0.5))
            {
                finalHeight = PASTER_SLIDE*(1+0.5) ;
            }
            if (finalHeight < PASTER_SLIDE*(1-0.5))
            {
                finalHeight = PASTER_SLIDE*(1-0.5) ;
            }
            
            self.bounds = CGRectMake(self.bounds.origin.x,
                                     self.bounds.origin.y,
                                     finalWidth,
                                     finalHeight);
            self.btnSizeCtrl.frame = CGRectMake(self.bounds.size.width-BT_SLIDE,
                                                self.bounds.size.height-BT_SLIDE,
                                                BT_SLIDE,
                                                BT_SLIDE);
            
            prevPoint = [panGesture locationOfTouch:0 inView:self];
        }
        
        float angle = atan2([panGesture locationInView:self.superview].y - self.center.y,
                            [panGesture locationInView:self.superview].x - self.center.x);
        float angleDiff = deltaAngle - angle;
        self.transform = CGAffineTransformMakeRotation(-angleDiff);
        
        [self setNeedsDisplay];
    }
    else if([panGesture state] == UIGestureRecognizerStateEnded)
    {
        prevPoint = [panGesture locationInView:self];
        [self setNeedsDisplay];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.isOnFirst = YES;
    
    if([self.delegate respondsToSelector:@selector(makePasterBecomeFirst:)])
        [self.delegate makePasterBecomeFirst:self.pasterID];
    
    UITouch *touch = [touches anyObject];
    touchStart = [touch locationInView:self.superview];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];
    if(CGRectContainsPoint(self.btnSizeCtrl.frame, touchLocation))
    {
        return;
    }
    
    CGPoint touch = [[touches anyObject] locationInView:self.superview];
    
    [self translateUsingTouchLocation:touch];
    
    touchStart = touch;
}

-(void)translateUsingTouchLocation:(CGPoint)touchPoint
{
    CGPoint newCenter = CGPointMake(self.center.x + touchPoint.x - touchStart.x,
                                    self.center.y + touchPoint.y - touchStart.y);
    
    CGFloat midPointX = CGRectGetMidX(self.bounds);
    if(newCenter.x > self.superview.bounds.size.width - midPointX + SECURITY_LENGTH)
    {
        newCenter.x = self.superview.bounds.size.width - midPointX + SECURITY_LENGTH;
    }
    
    if(newCenter.x < midPointX - SECURITY_LENGTH)
    {
        newCenter.x = midPointX - SECURITY_LENGTH;
    }
    
    CGFloat midPointY = CGRectGetMidY(self.bounds);
    if(newCenter.y > self.superview.bounds.size.height - midPointY + SECURITY_LENGTH)
    {
        newCenter.y = self.superview.bounds.size.height - midPointY + SECURITY_LENGTH;
    }
    
    if(newCenter.y < midPointY - SECURITY_LENGTH)
    {
        newCenter.y = midPointY - SECURITY_LENGTH;
    }
    
    self.center = newCenter;
}


#pragma mark - Properties(属性函数)

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    CGRect rect = CGRectZero;
    CGFloat sliderContent = PASTER_SLIDE - FLEX_SLIDE * 2;
    rect.origin = CGPointMake(FLEX_SLIDE, FLEX_SLIDE);
    rect.size = CGSizeMake(sliderContent, sliderContent);
    self.imgContentView.frame = rect;
    
    self.imgContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}

-(void)setIsOnFirst:(BOOL)isOnFirst
{
    _isOnFirst = isOnFirst;
    
    self.btnDelete.hidden = !isOnFirst;
    self.btnSizeCtrl.hidden = !isOnFirst;
    self.imgContentView.layer.borderWidth = isOnFirst ? BORDER_LINE_WIDTH : 0.0f;
    
    if(isOnFirst)
    {
        NSLog(@"pasterID:%d is on", self.pasterID);
    }
}

-(void)setImagePaster:(UIImage *)imagePaster
{
    _imagePaster = imagePaster;
    self.imgContentView.image = imagePaster;
}

-(UIImageView *)imgContentView
{
    if(!_imgContentView)
    {
        CGRect rect = CGRectZero;
        CGFloat sliderContent = PASTER_SLIDE - FLEX_SLIDE * 2;
        rect.origin = CGPointMake(FLEX_SLIDE, FLEX_SLIDE);
        rect.size = CGSizeMake(sliderContent, sliderContent);
        
        _imgContentView = [[UIImageView alloc] initWithFrame:rect];
        _imgContentView.backgroundColor = nil;
        _imgContentView.layer.borderColor = [UIColor whiteColor].CGColor;
        _imgContentView.layer.borderWidth = BORDER_LINE_WIDTH;
        _imgContentView.layer.shouldRasterize = YES;
        _imgContentView.contentMode = UIViewContentModeScaleAspectFit;
        
        if(![_imgContentView superview])
        {
            [self addSubview:_imgContentView];
        }
    }
    
    return _imgContentView;
}

-(UIImageView *)btnSizeCtrl
{
    if(!_btnSizeCtrl)
    {
        _btnSizeCtrl = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width - BT_SLIDE,
                                                                    self.frame.size.height - BT_SLIDE,
                                                                    BT_SLIDE,
                                                                    BT_SLIDE)];
        _btnSizeCtrl.userInteractionEnabled = YES;
        _btnSizeCtrl.image = [UIImage imageNamed:@"bt_paster_transform"];
        
        UIPanGestureRecognizer *panResizeGesture = [[UIPanGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(resizeTranslate:)];
        [_btnSizeCtrl addGestureRecognizer:panResizeGesture];
        
        if(![_btnSizeCtrl superview])
        {
            [self addSubview:_btnSizeCtrl];
        }
        
    }
    
    return _btnSizeCtrl;
}

-(UIImageView *)btnDelete
{
    if(!_btnDelete)
    {
        CGRect btnRect = CGRectZero;
        btnRect.size = CGSizeMake(BT_SLIDE, BT_SLIDE);
        
        _btnDelete = [[UIImageView alloc]initWithFrame:btnRect];
        _btnDelete.userInteractionEnabled = YES;
        _btnDelete.image = [UIImage imageNamed:@"bt_paster_delete"];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                             action:@selector(btnDeletePressed:)];
        [_btnDelete addGestureRecognizer:tap];
        
        
        if(![_btnDelete superview])
        {
            [self addSubview:_btnDelete];
        }
    }
    
    return _btnDelete;
}

-(void)btnDeletePressed:(id)btnDel
{
    NSLog(@"btnDel");
    [self remove];
}

@end
